package com.valenx.distributedmulticamerasystem.slice;

import com.valenx.distributedmulticamerasystem.CameraAbility;
import com.valenx.distributedmulticamerasystem.ResourceTable;

import com.valenx.distributedmulticamerasystem.utils.DeviceUtil;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.Component;
import ohos.agp.components.DirectionalLayout;
import ohos.data.distributed.common.KvManagerConfig;
import ohos.data.distributed.common.KvManagerFactory;
import ohos.distributedschedule.interwork.DeviceInfo;
import ohos.distributedschedule.interwork.DeviceManager;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

import java.util.ArrayList;
import java.util.List;

//主页面
public class MainAbilitySlice extends AbilitySlice implements Component.ClickedListener {
    //日志相关
    static final String TAG = MainAbilitySlice.class.getSimpleName();
    static final HiLogLabel LOG_LABEL = new HiLogLabel(HiLog.LOG_APP, 0x00102, TAG);

    private DirectionalLayout singleLayout; //“单机位”按钮
    private DirectionalLayout doubleLayout; //“双机位”按钮
    private DirectionalLayout tripleLayout; //“三机位”按钮
    private List<DeviceInfo> deviceInfoList = new ArrayList<>();//分布式网络下所有在线设备列表

//===================================================onStart===================================================
//=============================================================================================================
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        initComponent();
    }
//=============================================================================================================

    //初始化主界面按钮，并添加监听事件
    private void initComponent() {
        singleLayout = findComponentById(ResourceTable.Id_Single_Layout);
        doubleLayout = findComponentById(ResourceTable.Id_double_Layout);
        tripleLayout = findComponentById(ResourceTable.Id_triple_Layout);
        singleLayout.setClickedListener(this);
        doubleLayout.setClickedListener(this);
        tripleLayout.setClickedListener(this);
    }
//=============================================================================================================




//***************************************************单击事件***************************************************

    @Override
    public void onClick(Component component) {
        if (component == null) return;

        //点击“单机位”
        if (component == singleLayout) {
            startCameraAbility();
        }
//-------------------------------------------------------------------------------------------------------------

        //点击“双机位”
        else if (component == doubleLayout) {
            showDevicesDialog(1);
        }
//-------------------------------------------------------------------------------------------------------------

        //点击“三机位”
        else if (component == tripleLayout) {
            showDevicesDialog(2);
        }
    }
//*************************************************************************************************************




//***************************************************设备选择***************************************************

    //显示设备选择框
    private void showDevicesDialog(int checkNum) {
        if (deviceInfoList.size() > 0) {//如果设备列表非空，则先清空列表
            deviceInfoList.clear();
        }
        //获取分布式网络下所有在线设备列表
        deviceInfoList.addAll(DeviceManager
                .getDeviceList(ohos.distributedschedule.interwork.DeviceInfo.FLAG_GET_ONLINE_DEVICE));
        HiLog.info(LOG_LABEL, "当前分布式网络下所有在线设备数量:" + deviceInfoList.size());
        //在弹框中显示设备列表
        new DeviceUtil.SelectDeviceDialog(this, deviceInfoList,checkNum, checkedDeviceInfoList -> {
            ArrayList<String> slaveDeviceIds = new ArrayList<>();
            for (DeviceInfo deviceInfo:checkedDeviceInfoList){
                String slaveDeviceId = deviceInfo.getDeviceId();
                slaveDeviceIds.add(slaveDeviceId);
                startSlaveCamera(slaveDeviceId,checkNum);
            }
            startMasterCamera(slaveDeviceIds,checkNum);
        }).show();
    }
//*************************************************************************************************************




//***************************************************启动页面***************************************************

    //启动主机
    private void startMasterCamera(ArrayList<String> slaveDeviceIds,int slaveNum) {
        HiLog.info(LOG_LABEL, "主机启动");

        //将【从机设备ID】和【主机标识符】传给主机相机页面
        Intent masterIntent = new Intent();
        masterIntent.setParam("DISTRIBUTED_MODE", true);
        masterIntent.setStringArrayListParam("DEVICE_ID_SLAVE", slaveDeviceIds);
        masterIntent.setParam("IS_MASTER", true);
        masterIntent.setParam("SLAVE_NUMBER", slaveNum);


        Operation operation = new Intent.OperationBuilder()
                .withDeviceId("")//启动主机
                .withBundleName(this.getBundleName())
                .withAbilityName(CameraAbility.class.getName())
                .build();
        masterIntent.setOperation(operation);
        startAbility(masterIntent);
    }
//-------------------------------------------------------------------------------------------------------------

    //启动从机
    private void startSlaveCamera(String slaveDeviceId,int slaveNum) {
        HiLog.info(LOG_LABEL, "从机启动");

        //获取主机设备ID和名称
        String masterDeviceId = KvManagerFactory.getInstance()
                .createKvManager(new KvManagerConfig(this)).getLocalDeviceInfo().getId();
        //将【主机设备ID】和【主机标识符】传给从机相机页面
        Intent slaveIntent = new Intent();
        slaveIntent.setParam("DISTRIBUTED_MODE", true);
        slaveIntent.setParam("DEVICE_ID_MASTER", masterDeviceId);
        slaveIntent.setParam("IS_MASTER", false);
        slaveIntent.setParam("SLAVER_NUMBER", slaveNum);

        Operation operation = new Intent.OperationBuilder()
                .withDeviceId(slaveDeviceId)//启动从机
                .withBundleName(this.getBundleName())
                .withAbilityName(CameraAbility.class.getName())
                .withFlags(Intent.FLAG_ABILITYSLICE_MULTI_DEVICE)
                .build();
        slaveIntent.setOperation(operation);
        startAbility(slaveIntent);
    }
//-------------------------------------------------------------------------------------------------------------

    //启动相机页面
    private void startCameraAbility() {
        Operation operation = new Intent.OperationBuilder()
                .withDeviceId("")
                .withBundleName(getBundleName())
                .withAbilityName(".CameraAbility")
                .build();
        Intent intent = new Intent();
        intent.setParam("IS_MASTER", true);
        intent.setOperation(operation);
        startAbility(intent);
    }
//*************************************************************************************************************

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}
